<template>
  <div class="supplier-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>供应商管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddSupplier">
              <el-icon><Plus /></el-icon>
              新增供应商
            </el-button>
            <el-button type="primary" @click="refreshData">
              <el-icon><RefreshRight /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索供应商名称或联系人"
          class="search-input"
          clearable
          @clear="handleSearch"
          @input="handleSearchInput"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
        
        <el-select v-model="filterStatus" placeholder="供应商状态" @change="handleFilterChange" clearable>
          <el-option label="全部" value="" />
          <el-option label="正常" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </div>
      
      <!-- 供应商列表 -->
      <el-table
        :data="displayedSuppliers"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="供应商名称" min-width="150" />
        <el-table-column prop="contactPerson" label="联系人" min-width="120" />
        <el-table-column prop="phone" label="联系电话" min-width="150" />
        <el-table-column prop="email" label="电子邮箱" min-width="200" />
        <el-table-column prop="address" label="地址" min-width="250" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleViewOrders(scope.row)"
            >
              订单
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleEditSupplier(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除该供应商吗？"
              @confirm="handleDeleteSupplier(scope.row.id)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button
                  size="small"
                  type="danger"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 供应商表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑供应商' : '新增供应商'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="supplierFormRef"
        :model="supplierForm"
        :rules="supplierRules"
        label-width="100px"
      >
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="supplierForm.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="supplierForm.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="supplierForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="supplierForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="supplierForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="supplierForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="supplierForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSupplier" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Plus, 
  RefreshRight,
  Search
} from '@element-plus/icons-vue'
import {
  getAllSuppliers,
  getSupplierById,
  createSupplier,
  updateSupplier,
  deleteSupplier
} from '@/api/inventory'

const router = useRouter()

// 页面数据
const loading = ref(false)
const supplierList = ref([])

// 搜索和筛选
const searchKeyword = ref('')
const filterStatus = ref('')

// 分页相关
const pageSize = ref(10)
const currentPage = ref(1)

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const supplierFormRef = ref(null)

const supplierForm = reactive({
  id: null,
  name: '',
  contactPerson: '',
  phone: '',
  email: '',
  address: '',
  status: 1,
  remarks: ''
})

const supplierRules = {
  name: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  contactPerson: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ]
}

// 过滤后的供应商列表
const filteredSuppliers = computed(() => {
  let result = [...supplierList.value]
  
  // 搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      (item.name && item.name.toLowerCase().includes(keyword)) || 
      (item.contactPerson && item.contactPerson.toLowerCase().includes(keyword))
    )
  }
  
  // 状态过滤 - 只有当选择了特定状态时才过滤
  if (filterStatus.value !== '') {
    const status = parseInt(filterStatus.value);
    console.log("过滤状态:", status, "供应商列表:", result);
    // 确保不要过滤掉任何供应商
    result = result.filter(item => {
      console.log("供应商:", item.name, "状态:", item.status, "比较结果:", Number(item.status) === status);
      return Number(item.status) === status;
    });
  }
  
  return result
})

// 计算总条目数
const totalItems = computed(() => filteredSuppliers.value.length)

// 当前页显示的供应商
const displayedSuppliers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredSuppliers.value.slice(start, end)
})

// 搜索和筛选处理
const handleSearch = () => {
  currentPage.value = 1
}

const handleSearchInput = (value) => {
  if (!value) {
    handleSearch()
  }
}

const handleFilterChange = () => {
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 新增供应商
const handleAddSupplier = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑供应商
const handleEditSupplier = async (supplier) => {
  isEdit.value = true
  resetForm()
  
  try {
    loading.value = true
    const response = await getSupplierById(supplier.id)
    
    if (response.success) {
      const supplierData = response.data;
      // 确保状态值为数字类型（1或0）
      supplierData.status = supplierData.status === true ? 1 : 0;
      Object.assign(supplierForm, supplierData);
    } else {
      ElMessage.error(response.message || '获取供应商详情失败')
    }
  } catch (error) {
    console.error('获取供应商详情失败:', error)
    ElMessage.error('获取供应商详情失败')
  } finally {
    loading.value = false
    dialogVisible.value = true
  }
}

// 重置表单
const resetForm = () => {
  if (supplierFormRef.value) {
    supplierFormRef.value.resetFields()
  }
  
  supplierForm.id = null
  supplierForm.name = ''
  supplierForm.contactPerson = ''
  supplierForm.phone = ''
  supplierForm.email = ''
  supplierForm.address = ''
  supplierForm.status = 1
  supplierForm.remarks = ''
}

// 提交表单
const submitSupplier = async () => {
  if (!supplierFormRef.value) return
  
  await supplierFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      
      try {
        let response
        
        // 确保状态字段是正确的类型
        const formData = { ...supplierForm };
        // 后端期望状态为布尔值，将数字转为布尔值
        formData.status = formData.status === 1 ? true : false;
        
        // 如果是编辑
        if (isEdit.value) {
          console.log('更新供应商数据:', formData);
          response = await updateSupplier(formData.id, formData);
        } else {
          // 新增
          console.log('创建供应商数据:', formData);
          response = await createSupplier(formData);
        }
        
        if (response.success) {
          ElMessage.success(isEdit.value ? '更新供应商成功' : '创建供应商成功');
          dialogVisible.value = false;
          refreshData();
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新供应商失败' : '创建供应商失败'));
        }
      } catch (error) {
        console.error(isEdit.value ? '更新供应商失败:' : '创建供应商失败:', error);
        ElMessage.error(isEdit.value ? '更新供应商失败' : '创建供应商失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 删除供应商
const handleDeleteSupplier = async (id) => {
  try {
    loading.value = true
    const response = await deleteSupplier(id)
    
    if (response.success) {
      ElMessage.success('删除供应商成功')
      refreshData()
    } else {
      ElMessage.error(response.message || '删除供应商失败')
    }
  } catch (error) {
    console.error('删除供应商失败:', error)
    ElMessage.error('删除供应商失败')
  } finally {
    loading.value = false
  }
}

// 查看供应商订单
const handleViewOrders = (supplier) => {
  // 跳转到供应商订单页面
  ElMessage.info('功能即将上线...')
  // 可以在后续开发中实现
  // router.push(`/admin/inventory/supplier/${supplier.id}/orders`)
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    const response = await getAllSuppliers()
    
    if (response.success) {
      // 将后端返回的布尔值status转换为前端使用的数字类型(1/0)
      const suppliers = response.data || [];
      
      // 查看是否有数据返回及其状态
      console.log('获取到的供应商数据:', suppliers);
      
      suppliers.forEach(supplier => {
        supplier.status = supplier.status === true ? 1 : 0;
      });
      supplierList.value = suppliers;
    } else {
      ElMessage.error(response.message || '获取供应商列表失败')
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.supplier-management {
  padding-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 